const {
	reqGet,
	reqPost,
} = require('@utils/request')
const {
	$U_UserInfo,
	$U_SetItem,
	$U_GetItem,
} = require('@utils/storage')

module.exports = {
	/**
	 * 测试接口
	 * @return {[type]} [description]
	 */
	requestTestMethod() {
		let {
			store,
			testServerUrlComp,
			reqParamsComp,
			resParamsComp,
			formPath,
			formContentType,
			formMethod,
			alertDialog,
			alertText,
		} = this
		if (store.isLock) {
			$.messager.alert({
				title: "提示",
				msg: '当前为编辑模式，请先保存后再测试！'
			})
			return false
		}
		let currentAPI = store._currentCheckApiDetail
		if (!currentAPI || !currentAPI.id) {
			$.messager.alert({
				title: "提示",
				msg: '接口信息错误！'
			})
			return false
		}
		let path = formPath.textbox('getValue').trim()
		let method = formMethod.combobox('getValue')
		let contentType = formContentType.combobox('getValue')
		if (!path) {
			$.messager.alert({
				title: "提示",
				msg: '请填写正确请求路径！'
			})
			return false
		}
		let serverUrl = testServerUrlComp.textbox('getValue').trim()
		if (!serverUrl.replace(/^https?:\/\//, '')) {
			$.messager.alert({
				title: "提示",
				msg: '测试服务器地址错误！'
			})
			return false
		}
		let requestData = reqParamsComp.treegrid('getData')
		let requestParams = {}
		for (let i = 0; i < requestData.length; i++) {
			let data = requestData[i]
			let value = data.remark || ''
			value = value.replace(/@value=/, '').replace(/^['"`]|['"`]$/g, '')
			requestParams[data.name] = value || ''
		}
		let testHeader = $U_GetItem('testHeader', true)
		let params = {
			serverUrl,
			method,
			path,
			contentType,
			req_param_str: JSON.stringify(requestParams),
			req_header_str: testHeader,
		}
		store.isTest = true
		$.messager.progress()
		reqPost('/ult/api/test', params).then(result => {
			console.log('result', result)
			$.messager.progress('close')
			if (!result || result.error || result.catchErr) {
				alertDialog.dialog('setTitle', '提示')
				alertText.textbox('setValue', JSON.stringify(result, null, 5) || "什么都没返回！");
				alertDialog.dialog('open');
				// $.messager.alert({
				// 	title: '提示',
				// 	msg: JSON.stringify(result.catchErr, null, 5),
				// })
				return false
			}
			store.tmpResult = result || null
			store.tmpResponseParameterMap = {}
			store.tmpTestResponse = result
			let parameterData = resParamsComp.treegrid('getData')
			resParamsComp.treegrid('loadData', parameterData)
		})
	},

	/**
	 * 检查返回结果参数是否正确
	 * 1. 参数是否存在
	 * 2. 参数类型是否正确
	 * @param  {[type]} value [description]
	 * @param  {[type]} row   [description]
	 * @return {[type]}       [description]
	 */
	checkReponseParameter(value, row) {
		let {
			store,
		} = this
		if (!store.isTest)
			return row.remark
		let tmpResult = store.tmpResult
		let tmpMap = store.tmpResponseParameterMap
		if (!tmpResult || !tmpMap)
			return value
		tmpMap[row._treeId_] = row
		let result = {
			icon: 'ok',
			info: '参数正确！',
			style: '',
		}
		let keyArr = []
		let tmpRow = row
		while (tmpRow._parentId) {
			tmpRow = tmpMap[tmpRow._parentId]
			keyArr.push(tmpRow.name)
		}
		for (let i = keyArr.length - 1; i > -1; i--) {
			if (tmpResult)
				tmpResult = tmpResult[keyArr[i]]
		}
		if (Array.isArray(tmpResult))
			tmpResult = tmpResult[0]
		let resultValue = tmpResult && tmpResult[row.name]
		if (resultValue === undefined) {
			result.icon = 'cancel'
			result.style = 'color:red;'
			result.info = '参数不存在！'
		} else if ($._ulType(resultValue) != row.type) {
			result.icon = 'cancel'
			result.style = 'color:red;'
			result.info = `值类型错误！[${$._ulType(resultValue)}]`
		}
		return `<span style="${result.style}"><img src="/easyui/themes/icons/${result.icon}.png">&nbsp;${result.info}</span>`
	},

	updateTestServerUrl(e) {
		let {
			store,
			testServerUrlComp,
		} = this
		let serverUrl = testServerUrlComp.textbox('getValue').trim()
		serverUrl = /^https?:\/\//.test(serverUrl) ? serverUrl : `http://${serverUrl}`
		if (store.isLock) {
			store.editProjectData.testServerUrl = serverUrl
		}
		reqPost('/ult/project/edit', {
			project_id: store.projectId,
			test_server_url: serverUrl,
		}).then(result => {
			console.log(result)
		})
	},

	/**
	 * [responseOnLoadSuccess description]
	 * @return {[type]} [description]
	 */
	responseOnLoadSuccess() {
		let {
			store
		} = this
		store.isTest = store.isTest && false
	},

	/**
	 * 编辑测试请求值
	 * @param  {[type]} e [description]
	 * @return {[type]}   [description]
	 */
	editTestRequestValue(e) {
		let {
			store,
			reqParamsComp,
		} = this
		let current = store.reqCurrent
		let row = current.editValueRow
		reqParamsComp.treegrid('beginEdit', row._treeId_);
	},

	/**
	 * 添加测试header
	 */
	addTestHeader() {
		let {
			store,
			testHeaderText,
			testHeaderDialog,
		} = this
		if (store.isLock) {
			$.messager.alert({
				title: "提示",
				msg: '当前为编辑模式，请先保存后再添加测试header！'
			})
			return false
		}
		let testHeader = $U_GetItem('testHeader') || {}
		testHeader = JSON.stringify(testHeader, null, 5)
		testHeaderText.textbox('setValue', testHeader || '')
		testHeaderDialog.dialog('open')
	},

	/**
	 * [saveTestHeader description]
	 * @return {[type]} [description]
	 */
	saveTestHeader() {
		let {
			testHeaderText,
			testHeaderDialog,
		} = this
		let JSONData = null
		let value = testHeaderText.textbox('getValue')
		try {
			JSONData = JSON.parse(value)
		} catch (e) {
			try {
				JSONData = new Function(`return ${value};`)()
			} catch (e) {
				JSONData = null
			}
		}
		if (!JSONData || typeof JSONData != 'object') {
			alert('导入数据错误')
			return false
		}
		$U_SetItem('testHeader', JSONData)
		testHeaderDialog.dialog('close')
	},

	showTestResponse() {
		let {
			store,
			alertText,
			alertDialog,
		} = this
		if (!store.tmpTestResponse) {
			$.messager.alert({
				title: '提示',
				msg: '没有返回参数！再试试！',
			})
			return false
		}
		alertDialog.dialog('setTitle', '原始返回值')
		alertText.textbox('setValue', JSON.stringify(store.tmpTestResponse, null, 5));
		alertDialog.dialog('open');
	},
}